package com.lemon.springcloud.core.config;

import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;

/**
 * @author hdzhang
 * @ClassName LemonDefaultApplicationConf
 * @desc
 * @Date 2018/9/8 18:57
 * @Version 1.0
 **/
public class LemonDefaultApplicationConf {

    private static final String LEMON_BOOT_DEFAULT_CONF_RESOURCE_LOCATION = "META-INF/lemon-default-config.properties";

    /**
     * 默认配置参数
     */
    private static Properties defaultProperties;

    /**
     * 如果properties没有定义內建的默认值，将会自动使用默认配置，否则使用定义的
     *
     * @param definedProp defined properties
     */
    public static void cover(Map<String, Object> definedProp) {
        if (defaultProperties == null) {
            return;
        }

        for (Object pk : defaultProperties.keySet()) {
            if (definedProp.containsKey(pk)) {
                continue;
            }
            definedProp.put(String.valueOf(pk), defaultProperties.get(pk));
        }
    }

    /**
     * 初始化配置
     *
     * @param classLoader class loader
     */
    public static void init(ClassLoader classLoader) {
        Enumeration<URL> urls;
        try {
            urls = ClassLoader.getSystemResources(LEMON_BOOT_DEFAULT_CONF_RESOURCE_LOCATION);

            Properties prop;
            defaultProperties = new Properties();
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                prop = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                for (Object pk : prop.keySet()) {
                    defaultProperties.put(pk, prop.get(pk));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
